﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Timers;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using LotteryNumsCollect.LotterySrv;
namespace LotteryNumsCollect
{
    class Collect
    {
        static System.Timers.Timer timerSSC = new System.Timers.Timer(10 * 1000);
        static System.Timers.Timer timer3D = new System.Timers.Timer(60 * 1000);
        static System.Timers.Timer timerSSQ = new System.Timers.Timer(60 * 1000);
        static LotteryNumsInfo SSCInfo =new LotteryNumsInfo();
        static LotteryNumsInfo SSQInfo = new LotteryNumsInfo();
        static LotteryNumsInfo _3DInfo = new LotteryNumsInfo();
        static string SSCurl_backUrl = "http://video.shishicai.cn/haoma/cqssc/list/120.aspx";
        static string SSCurl = "http://video.shishicai.cn/haoma/cqssc/list/{0}.aspx";
        static string _3Durl = "http://kaijiang.zhcw.com/zhcw/inc/3d/3d_index.jsp?issue={0}";
        static string SSQurl = "http://www.zhcw.com/ssq/";
        static  LotteryServiceClient s;
        static object obj_lockSSC = new object();
        static object obj_lockSSQ = new object();
        static object obj_lock3D = new object();
        static void Main(string[] args)
        {
            //Paijiang p = new Paijiang();
            //p.GoPaiJiang(LotteryType.SSC);
            s = WcfProxy.GetProxy;
            timerSSC.Elapsed += new ElapsedEventHandler(timerSSC_Elapsed);
            timer3D.Elapsed += new ElapsedEventHandler(timer3D_Elapsed);
            timerSSQ.Elapsed += new ElapsedEventHandler(timerSSQ_Elapsed);
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThSSC_Fun));
            ThreadPool.QueueUserWorkItem(new WaitCallback(Th3D_Fun));
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThSSQ_Fun));
            Console.Read();
        }
        static void ThSSC_Fun(Object stateInfo)
        {
            SSCInfo = SetLotteryNumsInfo((int)LotteryType.SSC);
            timerSSC_Elapsed(null, null);
            timerSSC.Start();
        }
        static void ThSSQ_Fun(Object stateInfo)
        {
            SSQInfo = SetLotteryNumsInfo((int)LotteryType.SSQ);
            timerSSQ_Elapsed(null, null);
            timerSSQ.Start();
        }
        static void Th3D_Fun(Object stateInfo)
        {
            _3DInfo = SetLotteryNumsInfo((int)LotteryType._3D);
            timer3D_Elapsed(null, null);
            timer3D.Start();
        }
        static LotteryNumsInfo SetLotteryNumsInfo(int type)
        {
            LotteryNumsInfo l = s.GetCurrenIssuNo(type);
            if (l == null)
            {
                l = s.GetLastLotteryNum(type);
                if (l == null)
                    throw new Exception();
                l = CreateModel(l);
                s.InsertLotteryNums(l);
            }
            return l;
        }
        static void timerSSQ_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                lock (obj_lockSSQ)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("SSQ===>" + System.DateTime.Now.ToString() + ",开始采集");
                    string data = GetSSQNums(SSQInfo.IssueNo);
                    if (data != string.Empty)
                    {
                        SSQInfo.LotteryNums = data;
                        SSQInfo.UpdateUser = "autoCollect";
                        SSQInfo.UpdateTime = System.DateTime.Now;
                        s.UpdateLotteryNums(SSQInfo);
                        LotteryNumsInfo l = CreateModel(SSQInfo);
                        LotteryNumsInfo current = s.GetCurrenIssuNo((int)LotteryType.SSQ);
                        if (current == null || Convert.ToInt64(current.IssueNo) < Convert.ToInt64(l.IssueNo))
                        {
                            int result = s.InsertLotteryNums(l);
                            if (result > 0)
                                ThreadPool.QueueUserWorkItem(new WaitCallback(SSQPaiJiang));
                        }
                        sb.AppendLine("SSQ===>" + System.DateTime.Now.ToString() + ",期号:" + SSCInfo.IssueNo);
                        sb.AppendLine("SSQ===>" + System.DateTime.Now.ToString() + ",开奖号码:" + SSCInfo.LotteryNums);
                        SSQInfo = SetLotteryNumsInfo((int)LotteryType.SSQ);
                        TimeSpan ts = SSQInfo.LotteryDate.AddMinutes(5) - System.DateTime.Now;
                        
                        if (ts.TotalSeconds > 0)
                        {
                            timer3D.Stop();
                            sb.AppendLine("SSQ===>" + System.DateTime.Now.ToString() + ",暂停采集(分):" + ts.Milliseconds.ToString("F2"));
                            Console.WriteLine(sb.ToString());
                            Thread.Sleep(Convert.ToInt32(ts.TotalMilliseconds));
                            timer3D.Start();
                        }

                    }
                    else
                    {
                        TimeSpan ts = SSQInfo.LotteryDate.AddMinutes(5) - System.DateTime.Now;
                        if (ts.TotalSeconds > 0)
                        {
                            timerSSQ.Stop();
                            sb.AppendLine("SSQ===>" + System.DateTime.Now.ToString() + ",暂停采集(分):" + ts.TotalMinutes.ToString("F2"));
                            Console.WriteLine(sb.ToString());
                            SSQInfo = s.GetCurrenIssuNo((int)LotteryType.SSQ);
                            Thread.Sleep(Convert.ToInt32(ts.TotalMilliseconds));
                            timerSSQ.Start();
                        }
                        else
                        {
                            sb.AppendLine("SSQ===>" + System.DateTime.Now.ToString() + ",未采集到数据");
                            Console.WriteLine(sb.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("SSQ Exception:" + ex.Message);
            }
        }
        static void timer3D_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                lock (obj_lock3D)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("3D===>" + System.DateTime.Now.ToString() + ",开始采集");
                    string data = Get3DNums(_3DInfo.IssueNo);
                    if (data != string.Empty)
                    {
                        _3DInfo.LotteryNums = data;
                        _3DInfo.UpdateUser = "autoCollect";
                        _3DInfo.UpdateTime = System.DateTime.Now;
                        s.UpdateLotteryNums(_3DInfo);
                        LotteryNumsInfo l = CreateModel(_3DInfo);
                        LotteryNumsInfo current = s.GetCurrenIssuNo((int)LotteryType._3D);
                        if (current == null || Convert.ToInt64(current.IssueNo) < Convert.ToInt64(l.IssueNo))
                        {
                            int result = s.InsertLotteryNums(l);
                            if (result > 0)
                                ThreadPool.QueueUserWorkItem(new WaitCallback(_3DPaiJiang));
                        }
                        sb.AppendLine("SSC===>" + System.DateTime.Now.ToString() + ",期号:" + SSCInfo.IssueNo);
                        sb.AppendLine("SSC===>" + System.DateTime.Now.ToString() + ",开奖号码:" + SSCInfo.LotteryNums);
                        _3DInfo = SetLotteryNumsInfo((int)LotteryType._3D);
                        TimeSpan ts = _3DInfo.LotteryDate.AddMinutes(5) - System.DateTime.Now;//3D延迟采集5分钟
                        if (ts.TotalSeconds > 0)
                        {
                            timer3D.Stop();
                            sb.AppendLine("3D===>" + System.DateTime.Now.ToString() + ",暂停采集(分):" + ts.TotalMinutes.ToString("F2"));
                            Console.WriteLine(sb.ToString());
                            Thread.Sleep(Convert.ToInt32(ts.TotalMilliseconds));
                            timer3D.Start();
                        }

                    }
                    else
                    {
                        TimeSpan ts = _3DInfo.LotteryDate.AddMinutes(5) - System.DateTime.Now;//3D延迟采集5分钟
                        if (ts.TotalSeconds > 0)
                        {
                            timer3D.Stop();
                            sb.AppendLine("3D===>" + System.DateTime.Now.ToString() + ",暂停采集(分):" + ts.TotalMinutes.ToString("F2"));
                            Console.WriteLine(sb.ToString());
                            _3DInfo = s.GetCurrenIssuNo((int)LotteryType._3D);
                            Thread.Sleep(Convert.ToInt32(ts.TotalMilliseconds));
                            timer3D.Start();
                        }
                        else
                        {
                            sb.AppendLine("3D===>" + System.DateTime.Now.ToString() + ",未采集到数据");
                            Console.WriteLine(sb.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("3D Exception:" + ex.Message);
            }
        }
        static void timerSSC_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                lock (obj_lockSSC)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("SSC===>" + System.DateTime.Now.ToString() + ",开始采集");
                    string data = GetSSCNums(SSCInfo.IssueNo);
                    if (data != string.Empty)
                    {
                        SSCInfo.LotteryNums = data;
                        SSCInfo.UpdateUser = "autoCollect";
                        SSCInfo.UpdateTime = System.DateTime.Now;
                        s.UpdateLotteryNums(SSCInfo);
                        LotteryNumsInfo l = CreateModel(SSCInfo);
                        LotteryNumsInfo current = s.GetCurrenIssuNo((int)LotteryType.SSC);
                        if (current == null || Convert.ToInt64(current.IssueNo) < Convert.ToInt64(l.IssueNo))
                        {
                            int result=s.InsertLotteryNums(l);
                            if (result > 0)
                                ThreadPool.QueueUserWorkItem(new WaitCallback(SSCPaiJiang));
                        }
                        sb.AppendLine("SSC===>" + System.DateTime.Now.ToString() + ",期号:"+SSCInfo.IssueNo);
                        sb.AppendLine("SSC===>" + System.DateTime.Now.ToString() + ",开奖号码:" + SSCInfo.LotteryNums);
                        SSCInfo = SetLotteryNumsInfo((int)LotteryType.SSC);
                        TimeSpan ts = SSCInfo.LotteryDate.AddSeconds(25) - System.DateTime.Now;
                        if (ts.TotalSeconds > 10)
                        {
                            timerSSC.Stop();
                            sb.AppendLine("SSC===>" + System.DateTime.Now.ToString() + ",暂停采集(秒):" + ts.TotalSeconds.ToString("F2"));
                            Console.WriteLine(sb.ToString());
                            Thread.Sleep(Convert.ToInt32(ts.TotalMilliseconds));
                            timerSSC.Start();
                        }

                    }
                    else
                    {
                        TimeSpan ts = SSCInfo.LotteryDate.AddSeconds(25) - System.DateTime.Now;
                        if (ts.TotalSeconds > 10)
                        {
                            timerSSC.Stop();
                            sb.AppendLine("SSC===>" + System.DateTime.Now.ToString() + ",暂停采集(秒):" + ts.TotalSeconds.ToString("F2"));
                            Console.WriteLine(sb.ToString());
                            SSCInfo = s.GetCurrenIssuNo((int)LotteryType.SSC);
                            Thread.Sleep(Convert.ToInt32(ts.TotalMilliseconds));
                            timerSSC.Start();
                        }
                        else
                        {
                            sb.AppendLine("SSC===>" + System.DateTime.Now.ToString() + ",未采集到数据");
                            Console.WriteLine(sb.ToString());
                        }
                    }
                   
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("SSC Exception:" + ex.Message);
            }
        }
        static string GetSSCNums(string IssuNo)
        {
            try
            {
                SSCurl = string.Format(SSCurl, IssuNo.Substring(0, 4) + "-" + IssuNo.Substring(4, 2) + "-" + IssuNo.Substring(6, 2));
                string html = GetHttpWebRequest(SSCurl);
                if (html == string.Empty)
                    html = GetHttpWebRequest(SSCurl_backUrl);
                SSCurl = "http://video.shishicai.cn/haoma/cqssc/list/{0}.aspx";
                IssuNo = IssuNo.Substring(0, 8) + "-" + IssuNo.Substring(8, 3);
                string data = string.Empty;
                if (html.IndexOf("var listIssue = [{\"BonusNumberString\":\"") > -1
                    && html.IndexOf("var stringBuilder = [];") > -1)
                {
                    data = html.Substring(html.IndexOf("var listIssue = [{\"BonusNumberString\":\"") + 16,
                                  html.IndexOf("var stringBuilder = [];") - html.IndexOf("var listIssue = [{\"BonusNumberString\":\"") - 16);
                }
                if (data.IndexOf("\"IssueNumber\":\"" + IssuNo + "\"}") > -1)
                {
                    data = data.Substring(data.IndexOf("\"IssueNumber\":\"" + IssuNo + "\"}") - 67, 95);
                }
                data = data.Replace("\"BonusNumberString\":", "").Replace("\"BonusTime\":", "")
                           .Replace("\"IssueNumber\":", "").Replace("\",\"", "$").Replace("\"", "");
                string[] arr = data.Split('$');
                if (arr.Length < 3)
                    return string.Empty;
                if (arr[0].Replace(",", "").Length < 5)
                    return string.Empty;
                arr[0] = arr[0].Replace(",", "").Substring(0, 5);
                if (arr[2] == IssuNo)
                    return arr[0];
                else
                    return string.Empty;
                //if (html.Length==0||html.IndexOf("var listIssue = [{\"BonusNumberString\":\"") < 0)
                //    throw new Exception();
                //string data = html.Substring(html.IndexOf("var listIssue = [{\"BonusNumberString\":\"") + 18, 95);
                //data = data.Replace("\"BonusNumberString\":", "").Replace("\"BonusTime\":", "")
                //           .Replace("\"IssueNumber\":", "").Replace("\",\"", "$").Replace("\"","");
                //string[] arr = data.Split('$');
                //arr[0]=arr[0].Replace(",","").Substring(0,5);
                //arr[2] = arr[2].Replace("-", "");
                //if (arr[2] == IssuNo)
                //    return arr[0];
                //else
                //    return string.Empty;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        static string Get3DNums(string IssuNo)
        {
            try
            {
                string html = GetHttpWebRequest(string.Format(_3Durl, IssuNo));
                string data = string.Empty;
                if (html.IndexOf("中奖号码") > -1)
                    data = html.Substring(html.IndexOf("中奖号码") + 27, 72);
                data = Regex.Replace(data, @"<li[^>]*?>", "", RegexOptions.IgnoreCase).Replace("</li> ", "");
                return data;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        static string GetSSQNums(string IssuNo)
        {
            try
            {
                string html = GetHttpWebRequest(SSQurl);
                string data = string.Empty;
                if (html.IndexOf(string.Format("kjIssue\":\"{0}", IssuNo)) > -1)
                {
                    data = html.Substring(html.IndexOf(string.Format("kjIssue\":\"{0}", IssuNo)) + 20, 41);
                }
                data = data.Replace("kjTNum\":", "").Replace("kjZNum\":", "").Replace("\"", "");
                string[] arr = data.Split(',');
                if (arr.Length >= 2)
                    data = arr[1].Replace(" ",",") + "," + arr[0];
                return data;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        static string GetHttpWebRequest(string url)
        {
            string ip = string.Empty;
            string port = string.Empty;
            if (System.Configuration.ConfigurationManager.AppSettings["IpList"] != null)
            {
                List<string> iplist = System.Configuration.ConfigurationManager.AppSettings["IpList"].Split('|').ToList();
                if (iplist.Count > 0 && iplist[0].Contains(":"))
                {
                    Random r = new Random();
                    string ipStr = iplist[r.Next(iplist.Count - 1)];
                    ip = (ipStr.Split(':'))[0];
                    port = (ipStr.Split(':'))[1];
                }
                //ip = "218.28.111.46";
                //port = "8080";
            }
            Uri uri = new Uri(url);
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
            if (ip != string.Empty && port != string.Empty)
            {
                WebProxy proxy = new WebProxy(ip, Convert.ToInt32(port));
                myReq.Proxy = proxy;
            }
            myReq.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
            myReq.Accept = "*/*";
            myReq.KeepAlive = true;
            myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
            HttpWebResponse result = null;
            try
            {
                result = (HttpWebResponse)myReq.GetResponse();
            }
            catch(System.Net.WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                    return string.Empty;
            }
	        Stream receviceStream = result.GetResponseStream();
	        StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
	        string strHTML = readerOfStream.ReadToEnd();
	        readerOfStream.Close();
	        receviceStream.Close();
	        result.Close();
	        return strHTML;
        }
        static LotteryNumsInfo CreateModel(LotteryNumsInfo info)
        {
            LotteryNumsInfo lni = new LotteryNumsInfo();
            lni.AddTime = System.DateTime.Now;
            lni.AddUser = "autoCollect";
            lni.isDistributed = 0;
            lni.LotteryTypeID = info.LotteryTypeID;
            int lotterType = Convert.ToInt32(info.LotteryTypeID);
            lni.LotteryDate = info.LotteryDate;
            lni.IssueNo = info.IssueNo;
            if (lotterType == (int)LotteryType.SSC)
            {
                //期号    
                string no = (Convert.ToInt32(lni.IssueNo.Substring(8, 3)) + 1).ToString();
                lni.IssueNo = lni.IssueNo.Substring(0, 8);
                if (no.Length == 1)
                    no = "00" + no;
                if (no.Length == 2)
                    no = "0" + no;
                if (Convert.ToInt32(no) ==121)
                {
                    lni.IssueNo = lni.IssueNo.Substring(0, 4) + "-" + lni.IssueNo.Substring(4, 2) + "-" + lni.IssueNo.Substring(6, 2);
                    lni.IssueNo=Convert.ToDateTime(lni.IssueNo).AddDays(1).ToString("yyyyMMdd");
                    no = "001";
                }
                lni.IssueNo = lni.IssueNo + no;
                //开奖时间,10-22点十分钟一次，22-2点5分钟一次
                if ((lni.LotteryDate.Hour < 22 && lni.LotteryDate.Hour > 2))
                {
                    lni.LotteryDate = lni.LotteryDate.AddMinutes(10);
                }
                else if (lni.LotteryDate.ToString("HH:mm:ss") == "01:55:00")
                    lni.LotteryDate = lni.LotteryDate.AddHours(8).AddMinutes(5);
                else 
                    lni.LotteryDate = lni.LotteryDate.AddMinutes(5);

            }
            if (lotterType == (int)LotteryType._3D)
            {
                if (lni.LotteryDate.Month == 12 && lni.LotteryDate.Day == 31)
                {
                    lni.LotteryDate = lni.LotteryDate.AddYears(1).Date.AddHours(20).AddMinutes(30);
                    lni.IssueNo = lni.LotteryDate.AddYears(1).Year.ToString() + "001";
                }
                else
                {
                    lni.LotteryDate = lni.LotteryDate.AddDays(1);
                    string no = (Convert.ToInt32(lni.IssueNo.Substring(4, 3))+1).ToString();
                    lni.IssueNo = lni.IssueNo.Substring(0, 4);
                    if (no.Length == 2)
                        no = "0" + no;
                    if (no.Length == 1)
                        no = "00" + no;
                    lni.IssueNo = lni.IssueNo + no;
                }
            }
            if (lotterType == (int)LotteryType.SSQ)
            {
                if (lni.LotteryDate.Month == 12 && lni.LotteryDate.Day == 31)
                {
                    if(lni.LotteryDate.DayOfWeek==DayOfWeek.Thursday)
                        lni.LotteryDate = lni.LotteryDate.AddYears(1).Date.AddHours(21).AddMinutes(30).AddDays(3);
                    else
                        lni.LotteryDate = lni.LotteryDate.AddYears(1).Date.AddHours(21).AddMinutes(30).AddDays(2);
                    lni.IssueNo = lni.LotteryDate.AddYears(1).Year.ToString() + "001";
                }
                else
                {
                    if (lni.LotteryDate.DayOfWeek == DayOfWeek.Thursday)
                        lni.LotteryDate = lni.LotteryDate.AddDays(3);
                    else
                        lni.LotteryDate = lni.LotteryDate.AddDays(2);
                    string no = (Convert.ToInt32(lni.IssueNo.Substring(4, 3)) + 1).ToString();
                    lni.IssueNo = lni.IssueNo.Substring(0, 4);
                    if (no.Length == 2)
                        no = "0" + no;
                    if (no.Length == 1)
                        no = "00" + no;
                    lni.IssueNo = lni.IssueNo + no;
                }
            }
            
            return lni;
        }
        static void SSCPaiJiang(Object stateInfo)
        {
            Paijiang p = new Paijiang();
            p.GoPaiJiang(LotteryType.SSC);
        }
        static void _3DPaiJiang(Object stateInfo)
        {
            Paijiang p = new Paijiang();
            p.GoPaiJiang(LotteryType._3D);
        }
        static void SSQPaiJiang(Object stateInfo)
        {
            Paijiang p = new Paijiang();
            p.GoPaiJiang(LotteryType.SSQ);
        }
    }
    public enum LotteryType
    {
        SSC=1,
        _3D=2,
        SSQ=3
    }
}